<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言板</title>
    <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
    <link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet">
</head>
<body class="bg-gray-50">
    <div class="container mx-auto px-4 py-8">
        <!-- 发表留言区域 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
            <h2 class="text-xl font-bold mb-4">发表留言</h2>
            <form id="messageForm" class="space-y-4">
                <div>
                    <textarea id="messageContent" name="content" rows="4" 
                        class="w-full p-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
                        placeholder="写下你的想法..."></textarea>
                </div>
                <div>
                    <input type="file" class="filepond" name="images" multiple 
                        data-allow-multiple="true" 
                        data-max-files="5"
                        accept="image/*"/>
                </div>
                <div class="text-right">
                    <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition duration-300">
                        发表留言
                    </button>
                </div>
            </form>
        </div>

        <!-- 排序选项 -->
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold">全部留言</h2>
            <div class="flex space-x-4">
                <button id="sortByTime" class="px-4 py-2 rounded-lg transition duration-300" 
                    data-sort="time">按时间排序</button>
                <button id="sortByLikes" class="px-4 py-2 rounded-lg transition duration-300" 
                    data-sort="likes">按点赞排序</button>
            </div>
        </div>

        <!-- 留言列表 -->
        <div id="messageList" class="space-y-6"></div>

        <!-- 留言卡片模板 -->
        <template id="messageTemplate">
            <div class="message-card bg-white rounded-lg shadow-sm p-6">
                <div class="flex items-start space-x-4">
                    <img class="user-avatar w-12 h-12 rounded-full" src="" alt="用户头像">
                    <div class="flex-1">
                        <div class="flex justify-between items-start">
                            <div>
                                <h3 class="user-name font-bold"></h3>
                                <p class="created-time text-gray-500 text-sm"></p>
                            </div>
                            <div class="flex items-center space-x-2">
                                <button class="like-btn flex items-center space-x-1 text-gray-500 hover:text-green-600">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                                            d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z">
                                        </path>
                                    </svg>
                                    <span class="like-count">0</span>
                                </button>
                            </div>
                        </div>
                        <p class="message-content mt-2 text-gray-700"></p>
                        
                        <!-- 图片展示区 -->
                        <div class="image-gallery grid grid-cols-2 gap-2 mt-4"></div>
                        
                        <!-- 评论区 -->
                        <div class="mt-4 space-y-4">
                            <div class="flex items-center space-x-2">
                                <button class="comment-btn text-gray-500 hover:text-green-600 text-sm">
                                    回复
                                </button>
                            </div>
                            <div class="comment-form hidden">
                                <textarea class="w-full p-2 border rounded-lg text-sm" rows="2" placeholder="写下你的回复..."></textarea>
                                <div class="text-right mt-2">
                                    <button class="submit-comment bg-green-600 text-white px-4 py-1 rounded-lg text-sm hover:bg-green-700">
                                        发表回复
                                    </button>
                                </div>
                            </div>
                            <div class="comments-list pl-8 space-y-3"></div>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>

    <script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js"></script>
    <script src="https://unpkg.com/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.js"></script>
    <script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
    
    <script>
        // 注册 FilePond 插件
        FilePond.registerPlugin(FilePondPluginImagePreview);
        FilePond.registerPlugin(FilePondPluginFileValidateType);
        
        // 初始化 FilePond
        const pond = FilePond.create(document.querySelector('input[type="file"]'), {
            server: {
                url: '/api/upload',
                process: {
                    url: '/',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content
                    },
                    onload: response => {
                        const data = JSON.parse(response);
                        return data.url;
                    }
                }
            }
        });

        // 当前排序方式
        let currentSort = 'time';

        // 加载留言列表
        function loadMessages(sortBy = 'time') {
            fetch(`/api/message?sort=${sortBy}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        const messageList = document.getElementById('messageList');
                        messageList.innerHTML = '';
                        result.data.forEach(message => {
                            const messageElement = renderMessage(message);
                            messageList.appendChild(messageElement);
                        });
                    } else {
                        alert(result.msg || '加载失败');
                    }
                })
                .catch(error => console.error('Error loading messages:', error));
        }

        // 渲染单条留言
        function renderMessage(message) {
            const template = document.getElementById('messageTemplate');
            const clone = template.content.cloneNode(true);
            const messageCard = clone.querySelector('.message-card');
            
            // Set message card ID
            messageCard.id = `message-${message.id}`;
            
            // 设置基本信息
            messageCard.querySelector('.user-avatar').src = message.avatar || '/static/images/default-avatar.png';
            messageCard.querySelector('.user-name').textContent = message.nickname || message.username;
            messageCard.querySelector('.created-time').textContent = message.created_time;
            messageCard.querySelector('.message-content').textContent = message.content;
            
            // Set like button state and count
            const likeBtn = messageCard.querySelector('.like-btn');
            if (message.is_liked) {
                likeBtn.classList.add('text-green-600');
            }
            messageCard.querySelector('.like-count').textContent = message.like_count;
            
            // 渲染图片
            const gallery = messageCard.querySelector('.image-gallery');
            if (message.images && message.images.length > 0) {
                gallery.style.display = 'grid';
                message.images.forEach(url => {
                    const img = document.createElement('img');
                    img.src = url;
                    img.className = 'w-full h-48 object-cover rounded-lg cursor-pointer';
                    img.onclick = () => window.open(url, '_blank');
                    gallery.appendChild(img);
                });
            } else {
                gallery.style.display = 'none';
            }
            
            // 渲染评论
            const commentsList = messageCard.querySelector('.comments-list');
            if (message.comments && message.comments.length > 0) {
                message.comments.forEach(comment => {
                    const commentElement = renderComment(comment);
                    commentsList.appendChild(commentElement);
                });
            }
            
            // 添加事件监听器
            messageCard.querySelector('.like-btn').onclick = () => toggleLike(message.id);
            const commentBtn = messageCard.querySelector('.comment-btn');
            const commentForm = messageCard.querySelector('.comment-form');
            
            commentBtn.onclick = () => {
                commentForm.classList.toggle('hidden');
            };
            
            const submitCommentBtn = messageCard.querySelector('.submit-comment');
            submitCommentBtn.onclick = () => {
                const content = commentForm.querySelector('textarea').value;
                submitComment(message.id, null, content);
            };
            
            return messageCard;
        }

        // 渲染评论
        function renderComment(comment) {
            const div = document.createElement('div');
            div.className = 'bg-gray-50 rounded p-3';
            div.innerHTML = `
                <div class="flex items-start space-x-2">
                    <img src="${comment.avatar || '/static/images/default-avatar.png'}" 
                         class="w-8 h-8 rounded-full">
                    <div class="flex-1">
                        <div class="flex justify-between">
                            <span class="font-semibold">${comment.nickname || comment.username}</span>
                            <span class="text-gray-500 text-sm">${comment.created_time}</span>
                        </div>
                        <p class="text-sm mt-1">${comment.content}</p>
                        ${comment.replies ? renderReplies(comment.replies) : ''}
                    </div>
                </div>
            `;
            return div;
        }

        // 渲染回复
        function renderReplies(replies) {
            return `
                <div class="pl-8 mt-2 space-y-2">
                    ${replies.map(reply => `
                        <div class="text-sm">
                            <span class="font-semibold">${reply.nickname || reply.username}</span>
                            回复
                            <span class="font-semibold">${reply.parent_nickname || reply.parent_username}</span>：
                            ${reply.content}
                        </div>
                    `).join('')}
                </div>
            `;
        }

        // 切换点赞状态
        function toggleLike(messageId) {
            fetch(`/api/message/${messageId}/like`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    // Update like count immediately
                    const messageCard = document.querySelector(`#message-${messageId}`);
                    const likeBtn = messageCard.querySelector('.like-btn');
                    const likeCount = messageCard.querySelector('.like-count');
                    likeCount.textContent = result.data.like_count;
                    likeBtn.classList.toggle('text-green-600', result.data.is_liked);
                } else {
                    alert(result.msg || '操作失败');
                }
            })
            .catch(error => console.error('Error toggling like:', error));
        }

        // 提交评论
        function submitComment(messageId, parentId, content) {
            if (!content.trim()) {
                alert('请输入评论内容');
                return;
            }
            
            fetch(`/api/message/${messageId}/comment`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content, parent_id: parentId })
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    // 重新加载消息列表以显示新评论
                    loadMessages(currentSort);
                    // 清空并隐藏评论框
                    const messageCard = document.querySelector(`#message-${messageId}`);
                    const commentForm = messageCard.querySelector('.comment-form');
                    commentForm.querySelector('textarea').value = '';
                    commentForm.classList.add('hidden');
                } else {
                    alert(result.msg || '评论失败');
                }
            })
            .catch(error => {
                console.error('Error submitting comment:', error);
                alert('评论失败，请重试');
            });
        }

        // 发表留言
        document.getElementById('messageForm').onsubmit = async (e) => {
            e.preventDefault();
            const content = document.getElementById('messageContent').value.trim();
            const images = pond.getFiles().map(file => file.serverId);
            
            if (!content) {
                alert('请输入留言内容');
                return;
            }
            
            try {
                const response = await fetch('/api/message/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content, images })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    document.getElementById('messageForm').reset();
                    pond.removeFiles();
                    loadMessages(currentSort);
                } else {
                    alert(result.msg || '发表失败');
                }
            } catch (error) {
                console.error('Error creating message:', error);
                alert('发表失败，请重试');
            }
        };

        // 排序按钮事件
        document.querySelectorAll('[data-sort]').forEach(button => {
            button.onclick = (e) => {
                const sortBy = e.target.dataset.sort;
                currentSort = sortBy;
                document.querySelectorAll('[data-sort]').forEach(btn => {
                    btn.classList.remove('bg-green-600', 'text-white');
                });
                e.target.classList.add('bg-green-600', 'text-white');
                loadMessages(sortBy);
            };
        });

        // 初始加载
        document.addEventListener('DOMContentLoaded', () => {
            loadMessages('time');
            document.querySelector('[data-sort="time"]').classList.add('bg-green-600', 'text-white');
        });

        const profileSection = document.getElementById('profileSection');
        console.log('Profile section:', profileSection);
        console.log('Classes:', profileSection.classList);
        console.log('Computed style:', window.getComputedStyle(profileSection));
        console.log('Inner HTML:', profileSection.innerHTML);
    </script>
</body>
</html> 